<?php

namespace common\components\api_tool;

use Carbon\Carbon;
use common\components\wtools\tools\ArrayHelper;
use common\Tools;
use GuzzleHttp\Client;

class GylApi extends ApiTool
{
    public $apiUri = '/gylApi';
    public $token;
    public $key;

    public $proxy = [];

    /**
     * 设置token和key
     * @param $token
     * @param $key
     * @return $this
     */
    public function setTokenKey($token, $key)
    {
        $this->token = $token;
        $this->key = $key;
        return $this;
    }

    public function request($uri = "", $options = [], $method = "post", $isAuth = true)
    {
        $base_uri = $this->baseUri. $this->apiUri. $uri;
        $client = new Client(['base_uri' => $base_uri]);
        if ($isAuth) {
            $options['headers'] = [
                'Authorization' => 'Bearer '.$this->token,
            ];
            $options['form_params'] = $this->generateFormParams($options['form_params'] ?? []);
            if (isset($options['query'])) {
                $options['query'] = $this->generateFormParams($options['query']);
            }
        }
        $resp = $client->request($method, '', $options);
        $resp_cont = $resp->getBody()->getContents();
        $resp_cont_arr = Tools::isJson($resp_cont);
        return $resp_cont_arr;
    }

    /**
     * @param $user
     * @param array $form_params
     * @return array
     */
    public function generateFormParams($form_params = [])
    {
        $form_params['token'] = $this->token;
        $form_params['timestamp'] = Carbon::now()->timestamp;
        $form_params['nonce'] = $form_params['timestamp'].rand(10000000, 40000000);
        $p = $form_params;
        $p['key'] = $this->key;
        ksort($p);
        unset($p['sign']);
        $p_arr = [];
        foreach ($p as $k => $v) {
            $p_arr[] = $k."=".$v;
        }
        $p_str = ArrayHelper::arr2str($p_arr, '&');
        $form_params['sign'] = md5($p_str);
        unset($form_params['token']);
        return $form_params;
    }

    /**
     * @param $uri
     * @return string
     */
    public function getFullUrl($uri = "")
    {
        return $this->baseUri.$this->apiUri.$uri;
    }
}
